﻿using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FC.NPOI.Utils
{
    public static class NPOIHelper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="workbook"></param>
        /// <param name="list"></param>
        /// <param name="titles"></param>
        /// <param name="pps"></param>
        /// <returns></returns>
        private static ISheet CreateSheet<T>(this IWorkbook workbook, IList<T> list, IList<string> titles, IList<string> pps, IList<int> decimals = null, IList<int> times = null)
        {
            // 创建一个 NPOI工作表
            ISheet sheet = workbook.CreateSheet();

            // 创建首行 标题行
            IRow titleRow = sheet.CreateRow(0);

            // 创建样式 用于标题行
            ICellStyle style = workbook.CreateCellStyle();
            style.FillForegroundColor = HSSFColor.Grey25Percent.Index;  // 背景色
            style.FillPattern = FillPattern.SolidForeground;    //

            // 首行冻结
            sheet.CreateFreezePane(0, 1); 

            // 创建首行单元格 从 titles 取值
            for (int i = 0; i < titles.Count(); i++)
            {
                ICell cell = titleRow.CreateCell(i, CellType.String);
                cell.SetCellValue(titles[i]);
                cell.CellStyle = style;
            }

            // 用反射
            Type type = typeof(T);
            PropertyInfo[] properties = type.GetProperties();

            for (int j = 0; j < list.Count(); j++)
            {
                IRow row = sheet.CreateRow(j + 1);
                for (int i = 0; i < pps.Count(); i++)
                {
                    ICell cell = row.CreateCell(i, CellType.String);
                    if (pps[i] == "TunnelLength" || pps[i] == "TunnelHeight" || pps[i] == "TunnelWidth")
                    {
                        decimal? d = (decimal?)properties.First(p => p.Name == pps[i]).GetValue(list[j], null);
                        string s = String.Format("{0:N2}", d);//.Replace(".00", "");
                        cell.SetCellValue(s);
                    }
                    else if (pps[i] == "CompletionDate")
                    {
                        DateTime? v = (DateTime?)properties.First(p => p.Name == pps[i]).GetValue(list[j], null);
                        cell.SetCellValue(v == null ? "" : v.Value.ToString("yyyy-MM-dd"));
                    }
                    else
                    {
                        object v = properties.First(p => p.Name == pps[i]).GetValue(list[j], null);
                        cell.SetCellValue(v == null ? "" : v.ToString());
                    }
                }
            }

            return sheet;
        }

    }
}
